package com.itruth.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.itruth.dao.ShareDao;
import com.itruth.dao.impl.ShareDaoImpl;
import com.itruth.entity.ShareEntity;
import com.opensymphony.xwork2.ActionSupport;

public class ShareAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6899423756361902568L;

	private ShareDao shareDao;
	
	public ShareAction () {
		shareDao = new ShareDaoImpl();
	}
	
	/**
	 * 查询分享数据
	 */
	public void query() {
		
		System.out.println("query");
		
		HttpServletRequest req = ServletActionContext.getRequest();
		HttpServletResponse res = ServletActionContext.getResponse();
		PrintWriter pw = null;
		res.setCharacterEncoding("UTF-8");
		
		try {
			
			pw = res.getWriter();
			
			String shareId = req.getParameter("shareId");
			String pullDownRefresh = req.getParameter("pullDownRefresh");
			
			System.out.println(shareId + ", " + pullDownRefresh);
			
			List<ShareEntity> shares = shareDao.query(parseString(shareId), parsePullDownRefresh(pullDownRefresh));
			
			JSONArray jArray = new JSONArray();
			
			for (ShareEntity se : shares) {
				jArray.add(se);
			}
			JSONObject json = new JSONObject();
			json.accumulate("shareData", jArray.toString());
			pw.write(json.toString());
			
			pw.flush();
		} catch (IOException e) {
			
			//TODO 服务器错误
			
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (null != pw) {
				pw.close();
				pw = null;
			}
			
		}
		
	}
	
	
	private int parseString(String str) {
		
		return Integer.parseInt(str);
		
	}
	
	/**
	 * 0--上一页
	 * 1--下一页
	 * @param str
	 * @return
	 */
	private boolean parsePullDownRefresh(String str) {
		
		int i = parseString(str);
		
		return i == 1;
		
	}
	
	
}
